import React, { useEffect, useRef, useState } from "react";
import { get } from "../../util/get";
import { Table, Tag, Space, Button, Modal, Form, Input, message, Select, TreeSelect } from "antd";
import { EditOutlined, DeleteOutlined, ExclamationCircleOutlined, LinkOutlined } from "@ant-design/icons"
import { post } from "../../util/post";
import EditRoleModal from "../../components/EditRoleModal";
import PubSub from "pubsub-js";
import LinkModal from "../../components/LinkModal";
import style from "./index.module.css"
const { Column } = Table;
const { confirm } = Modal;
const Role = () => {
    const token = localStorage.getItem('TOKEN')
    const [data, setData] = useState([])
    const [total, setTotal] = useState(0)
    const [page, setPage] = useState(1)
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [editV, setEditV] = useState(false)
    const [linkV, setLinkV] = useState(false)
    const ref = useRef()
    const getRoleList = async () => {
        const res = await get(`/user/role/list?page=${page}&limit=7`, token)
        const res2 = await get('/user/role/permissionList', token)
        const permissionVoList = res2.data.data
        const { msg, code, page: { list, totalCount } } = res.data
        if (!code) {
            const newList = list.map((i, index) => {
                const p = permissionVoList[index].permissionVoList;
                i.permissionVoList = p ? p : []
                return i;
            })
            setData(newList);
               setTotal(totalCount);
        }
        else message.error(msg)
    }
    useEffect(() => {
        getRoleList()
    }, [linkV,editV,page])
    const handleCancel = () => {
        setIsModalVisible(false);
    };
    const onFinish = async (values) => {
        console.log(values, 'post')
        const res = await post('/user/role/save', values, token)
        const { code, msg } = res.data;
        if (code === 0) {
            message.success(msg)
            setData([...data, values])
            setIsModalVisible(false)
            ref.current.resetFields();
        } else message.error(msg)
    };
    const onFinishFailed = (errorInfo) => {
        message.error(errorInfo);
    };
    const renderForm = () => {
        return (
            <Form name="basic" labelCol={{ span: 6 }}
                wrapperCol={{ span: 16 }}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
                autoComplete="off"
                ref={ref}
            >
                <Form.Item
                    label="名称"
                    name="name"
                    rules={[
                        {
                            required: true,
                            message: '此为必填项',
                        },
                    ]}
                >
                    <Input></Input>
                </Form.Item>
                <Form.Item
                    label="描述"
                    name="description"
                    rules={[
                        {
                            required: true,
                            message: '此为必填项',
                        },
                    ]}
                >
                    <Input></Input>
                </Form.Item>
                <Form.Item
                    wrapperCol={{
                        offset: 8,
                        span: 16,
                    }}
                >
                    <Button type="primary" htmlType="submit">
                        提交
                    </Button>
                </Form.Item>
            </Form>
        )
    }
    const handleEdit = (data) => {
        PubSub.publish('editRole', data)
        setEditV(true)
    }
    const handleDelete = (item) => {
        confirm({
            title: '你确定要删除该角色吗',
            icon: <ExclamationCircleOutlined />,
            onOk() {
                post('/user/permission/delete', [item.id], token).then(res => {
                    const { msg, code } = res.data
                    if (!code) {
                        message.success(msg);
                        const newData = data.filter(i => i.id === item.id)
                        setData(newData)
                    }
                    else message.error(msg);
                })
            },
            onCancel() {
            },
        })
    }
    const addResource = () => {
        setIsModalVisible(true)
    }
    const handleEditCancel = () => {
        setEditV(false);
    }
    const handleLink = (item) => {
        // console.log(item)
        PubSub.publish('linkrole', item)
        setLinkV(true)
    }
    return (
        <>
            <Button type="primary" className={style.add} shape="round" onClick={addResource}  >
                新增角色
            </Button>
            <Modal title="新增角色" visible={isModalVisible} footer={null} onCancel={handleCancel}>
                {
                    renderForm()
                }
            </Modal>
            <EditRoleModal v={editV} setV={setEditV}></EditRoleModal>
            <LinkModal v={linkV} setV={setLinkV}></LinkModal>
            <Table dataSource={data}
            pagination={{
                total,
                page,
                defaultPageSize:7,
                onChange:(page)=>{
                  setPage(page)
                }
              }}>
                <Column title="名称" dataIndex={"name"} key={"method"} />
                <Column title="描述" dataIndex={"description"} key={"description"} />
                <Column title="拥有资源" dataIndex={"permissionVoList"} key={"permissionVoList"} render={(i) => {
                    return <div>
                        {
                            i.map(item =><Tag>{item.description}</Tag>)
                        }
                    </div>
                }} />
                <Column title="操作" dataIndex={"action"} key={"action"} render={(_, item) => {
                    return (
                        <Space>
                            <Button shape="circle" onClick={() => handleLink(item)} type="dashed" icon={<LinkOutlined />} size={'large'}></Button>
                            <Button type="primary" onClick={() => handleEdit(item)} shape="circle" icon={<EditOutlined />} size={"large"} />
                            <Button type="primary" onClick={() => handleDelete(item)} danger shape="circle" icon={<DeleteOutlined />} size={"large"} />
                        </Space>
                    )
                }}>

                </Column>
            </Table>
        </>
    )
}
export default Role;
